package com.reggie.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.reggie.dto.DishDto;
import com.reggie.dto.OrdersDto;
import com.reggie.dto.SetmealDto;
import com.reggie.mapper.SetmealMapper;
import com.reggie.pojo.*;
import com.reggie.service.*;
import com.reggie.util.PageUtil;
import com.reggie.util.ResultUtil;
import com.reggie.util.SnowflakeIdWorkerUtil;
import com.reggie.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//订单请求映射类
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    OrderService orderService;
    @Autowired
    OrderdetailService orderdetailService;
    @Autowired
    ShoppingCartService shoppingCartService;
    @Autowired
    AddressBookService addressBookService;
    @Autowired
    DishService dishService;
    @Autowired
    SetmealMapper setmealMapper;
    @Autowired
    UserService userService;

    //分页查询多条订单信息
    @GetMapping("/page")
    public ResultUtil<PageUtil<Orders>> page(@RequestParam(value = "page", defaultValue = "0") int page,
                                             @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                             @RequestParam(value = "number", required = false) String number,
                                             @RequestParam(value = "beginTime", required = false) String beginTime,
                                             @RequestParam(value = "endTime", required = false) String endTime) {
        PageUtil<Orders> orderPage = orderService.findAll(page, pageSize, number, beginTime, endTime);
        if (orderPage == null) return ResultUtil.error("未查询到订单信息！");
        return ResultUtil.success(orderPage);
    }

    //修改订单状态
    @PutMapping
    public ResultUtil<String> editStatus(@RequestBody Orders orders){
        if (orderService.editStatus(orders.getStatus(), orders.getId())) return ResultUtil.success("编辑订单状态成功！");
        return ResultUtil.error("编辑订单状态失败！");
    }

    //添加订单
    @PostMapping("/submit")
    public ResultUtil<String> submit(@RequestBody Orders orders){
        Long id = new SnowflakeIdWorkerUtil(0,0).nextId();
        AddressBook addressBook = addressBookService.find(orders.getAddressBookId(), null, null);
        Map<String, Object> map = ThreadLocalUtil.get();
        orders.setId(id);
        orders.setNumber(String.valueOf(id));
        orders.setStatus(2);
        orders.setUserId(Long.valueOf((String) map.get("id")));
        Double totalAmount = 0.0;
        List<ShoppingCart> shoppingCarts = shoppingCartService.findAll(Long.valueOf((String) map.get("id")));
        for (ShoppingCart shoppingCart:shoppingCarts){
            totalAmount = totalAmount+shoppingCart.getAmount();
            OrderDetail orderDetail = new OrderDetail();
            Long id2 = new SnowflakeIdWorkerUtil(0,0).nextId();
            orderDetail.setId(id2);
            orderDetail.setName(addressBook.getConsignee());
            orderDetail.setImage((String) map.get("avatar"));
            orderDetail.setOrderId(id);
            if (shoppingCart.getDishId()!=null) orderDetail.setDishId(shoppingCart.getDishId());
            if (shoppingCart.getSetmealId()!=null) orderDetail.setDishId(shoppingCart.getSetmealId());
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setAmount(shoppingCart.getAmount());
            if(!orderdetailService.add(orderDetail)) return ResultUtil.error("添加订单详细信息失败！");
            if (!shoppingCartService.delete(shoppingCart)) return ResultUtil.error("添加订单详细信息失败！");
        }
        orders.setAmount(totalAmount);
        orders.setPhone((String) map.get("phone"));
        orders.setAddress(addressBook.getProvince_name()
                +":"+addressBook.getCity_name()
                +":"+addressBook.getDistrict_name()
                +":"+addressBook.getDetail());
        orders.setUserName((String) map.get("name"));
        orders.setConsignee(addressBook.getConsignee());
        if (!orderService.add(orders)) return ResultUtil.error("添加订单信息失败！");
        return ResultUtil.success("添加订单信息成功！");
    }

    //分页查询订单信息
    @GetMapping("/userPage")
    public ResultUtil<PageUtil<OrdersDto>> userPage(@RequestParam(value = "page", defaultValue = "0") Integer page,
                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize){
        Map<String, Object> map = ThreadLocalUtil.get();
        PageUtil<OrdersDto> ordersDtoPageUtil = new PageUtil<>();
        PageHelper.startPage(page, pageSize);
        List<OrdersDto> ordersDtoList = orderService.findByUserId(page, pageSize, Long.valueOf((String) map.get("id")));
        for (OrdersDto ordersDto:ordersDtoList){
            List<OrderDetail> orderDetails = orderdetailService.findByOrderId(ordersDto.getId());
            ordersDto.setOrderDetails(orderDetails);
        }
        Page<OrdersDto> ordersDtoPage = (Page<OrdersDto>)ordersDtoList;
        ordersDtoPageUtil.setTotal(ordersDtoPage.getTotal());
        ordersDtoPageUtil.setRecords(ordersDtoPage.getResult());
        if (ordersDtoList==null) return ResultUtil.error("查询订单信息失败！");
        return ResultUtil.success(ordersDtoPageUtil);
    }

    //再来一单
    @PostMapping("/again")
    public ResultUtil<String> again(@RequestBody Orders orders){
        Map<String, Object> map = ThreadLocalUtil.get();
        Orders orders1 = orderService.findById(orders.getId());
        List<OrderDetail> orderDetails = orderdetailService.findByOrderId(orders.getId());
        for (OrderDetail orderDetail:orderDetails){
            ShoppingCart shoppingCart = new ShoppingCart();
            Long id = new SnowflakeIdWorkerUtil(0,0).nextId();
            shoppingCart.setId(id);
            if (orderDetail.getDishId()!=null){
                DishDto dishDto = dishService.find(orderDetail.getDishId());
                shoppingCart.setName(dishDto.getName());
                shoppingCart.setImage(dishDto.getImage());
                shoppingCart.setDishId(orderDetail.getDishId());
            }
            if (orderDetail.getSetmealId()!=null){
                SetmealDto setmealDto = setmealMapper.find(orderDetail.getSetmealId());
                shoppingCart.setName(setmealDto.getName());
                shoppingCart.setImage(setmealDto.getImage());
                shoppingCart.setDishId(orderDetail.getSetmealId());
            }
            shoppingCart.setUserId(Long.valueOf((String) map.get("id")));
            shoppingCart.setNumber(orderDetail.getNumber());
            shoppingCart.setAmount(orderDetail.getAmount());
            if(!shoppingCartService.add(shoppingCart)) return ResultUtil.error("重建订单信息失败!");
        }
        return ResultUtil.success("重建订单信息成功！");
    }
}
